const fs = require('fs').promises;
const path = require('path');

class JSONDatabase {
  constructor(filename) {
    this.filepath = path.join(__dirname, 'data', filename);
  }

  async read() {
    try {
      const data = await fs.readFile(this.filepath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      return [];
    }
  }

  async write(data) {
    await fs.writeFile(this.filepath, JSON.stringify(data, null, 2));
  }

  async insert(item) {
    const records = await this.read();
    records.push({ ...item, id: Date.now() });
    await this.write(records);
    return item;
  }
}

// 初始化数据库实例
const usersDB = new JSONDatabase('users.json');
const messagesDB = new JSONDatabase('messages.json');

module.exports = { usersDB, messagesDB };
